<?php
/************************
 *  Codenova.pl Project
 *  Created by: Kamil Mrzygłód
 *
 *  (c) 2013 by Codenova.pl
 *  All Right Reserved
 ***********************/

namespace Modules\JasminumNewsletter\Controllers;
use Gotcha\App\Extensions\GotchaCulturesExtension;
use Gotcha\App\Extensions\GotchaErrorsExtension;
use Gotcha\App\Extensions\GotchaLogsExtension;
use Gotcha\App\Framework\Controller;
use Gotcha\App\Types\String;
use GotchaDatabase\JasminumNewsletterMails;

class DefaultController extends Controller {
    public function Index() {
        parent::View();
    }

    public function Send() {
        // Validation
        if (!isset($_POST['ReturnURL'])) {
            die('Error.');
        }

        if (empty($_POST['Email'])) {
            header('Location: '.GOTCHA_BASE_PATH.$_POST['ReturnURL'].'?errors=10');
            exit;
        }

        if (strlen($_POST['Email']) > 50) {
            header('Location: '.GOTCHA_BASE_PATH.$_POST['ReturnURL'].'?errors=20');
            exit;
        }

        if (!filter_var($_POST['Email'], FILTER_VALIDATE_EMAIL)) {
            header('Location: '.GOTCHA_BASE_PATH.$_POST['ReturnURL'].'?errors=30');
            exit;
        }

        // After positive validation we can save new newsletter
        // user to the databse
        $newsletter = new JasminumNewsletterMails();

        try {
            $newsletter->setMail($_POST['Email']);
            $newsletter->save();

            // Data is saved, return a view
            header('Location: '.GOTCHA_BASE_PATH.'/JasminumNewsletter/Congratulations');
            exit;
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }
    }

    public function Congratulations() {
        parent::View();
    }
}